package com.hxci.zhongjiahao.tool;

import com.hxci.zhongjiahao.pojo.Course;
import com.hxci.zhongjiahao.servcie.CorseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;

import java.util.List;
import java.util.function.Function;

@Configuration
public class CourseTools {

	@Autowired
	private CorseService corseService;

	public record AddCourseRequest(String cname, String mark, String tea, String category, Integer credit,
								   String semester) {
	}

	public record DeleteCourseRequest(String id) {
	}

	public record QueryTeacherRequest(String teacher) {
	}

	@Bean
	@Description("添加课程")
	public Function<AddCourseRequest, String> addCourse() {
		return req -> {
			try {
				Course c = new Course();
				c.setCname(req.cname);
				c.setMark(req.mark);
				c.setTea(req.tea);
				c.setCategory(req.category);
				c.setCredit(req.credit);
				c.setSemester(req.semester);
				corseService.save(c);
				return "课程添加成功";
			} catch (Exception e) {
				return "添加失败：" + e.getMessage();
			}
		};
	}

	@Bean
	@Description("删除课程")
	public Function<DeleteCourseRequest, String> deleteCourse() {
		return req -> {
			try {
				int res = corseService.del(req.id);
				return res > 0 ? "课程删除成功" : "删除失败，课程不存在";
			} catch (Exception e) {
				return "删除出错：" + e.getMessage();
			}
		};
	}

	@Bean
	@Description("查询教师课程")
	public Function<QueryTeacherRequest, List<Course>> getCourseDetails() {
		return request -> {
			System.out.println("查询教师课程请求，教师: " + request.teacher());
			try {
				return corseService.queryByTeacher(request.teacher());
			} catch (Exception e) {
				System.err.println("查询课程时发生错误: " + e.getMessage());
				return List.of();
			}
		};
	}
}
